package http

import (
	"encoding/json"
	"fmt"
	"net/url"

	"github.com/valyala/fasthttp"
)

func toValues(args map[string]interface{}) string {
	encoded := url.Values{}
	for k, v := range args {
		encoded.Set(k, fmt.Sprintf("%v", v))
	}
	return encoded.Encode()
}

func FastGet(url string, args map[string]interface{}) ([]byte, error) {
	uri := url + "?" + toValues(args)
	_, resp, err := fasthttp.Get(nil, uri)
	if err != nil {
		fmt.Println("请求失败:", err.Error())
		return nil, err
	}
	return resp, err
}

func FastPostForm(url string, args map[string]interface{}) ([]byte, error) {

	// 填充表单，类似于net/url
	params := &fasthttp.Args{}
	for s, i2 := range args {
		sprintf := fmt.Sprintf("%v", i2)
		params.Add(s, sprintf)
	}
	_, resp, err := fasthttp.Post(nil, url, params)
	if err != nil {
		fmt.Println("请求失败:", err.Error())
		return nil, err
	}
	return resp, nil
}

func FastPostJson(url string, args map[string]interface{}) ([]byte, error) {

	req := &fasthttp.Request{}
	req.SetRequestURI(url)

	marshal, _ := json.Marshal(args)
	req.SetBody(marshal)

	// 默认是application/x-www-form-urlencoded,其实无所谓
	req.Header.SetContentType("application/json")
	req.Header.SetMethod("POST")

	resp := &fasthttp.Response{}
	if err := fasthttp.Do(req, resp); err != nil {
		fmt.Println("请求失败:", err.Error())
		return nil, err
	}
	return resp.Body(), nil
}
